<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/11/6 15:04
 * Desc: 营销应用-优惠券
 */
class Model_Api_V2_Marketing_Strategy_Coupon extends Contract_Api_Marketing_Strategy
{
    private static $instance = null;

    private $type_id;

    private $application_name = '优惠券';

    private $application_code = 'coupon';

    private $icon = '&#xe641;';

    public function __construct($type_id)
    {
        $this->type_id = $type_id;
    }

    /**
     * @param int $type_id
     * @param array $params
     * @return Model_Api_V2_Marketing_Strategy_Coupon|null
     */
    public static function get_instance(int $type_id, array $params = array())
    {
        // 应用是否安装
        if (!St_Functions::is_normal_app_install('coupon')) {
            return null;
        }

        // 是否支持该产品类型
        $is_coupon_able = DB::select()
            ->from('model')
            ->where('id', '=', $type_id)
            ->and_where('is_couponable', '=', 1)
            ->execute()
            ->get('is_couponable');
        if (empty($is_coupon_able)) {
            return null;
        }

        if (is_null(self::$instance)) {
            self::$instance = new self($type_id);
        }

        return self::$instance;
    }

    /**
     * 检查是否支持对应产品
     * 支持返回code和中文名称
     * 不支持返回 false
     * @param $product_id
     * @return array|false 二维数组，防止某些应用有多个标签
     */
    public function is_support($product_id)
    {
        $now_time = time();
        $count    = DB::select()
            ->from(array('coupon', 'a'))
            ->join(array('coupon_pro', 'b'), 'left')
            ->on('a.id', '=', 'b.cid')
            ->where('a.isopen', '=', 1)
            ->and_where('a.isdel', '=', 0)
            ->and_where_open()
            ->where('a.typeid', '=', 0)
            ->where(DB::expr(" OR (sline_a.typeid=1 and FIND_IN_SET({$this->type_id},sline_a.modules))"))
            ->where(DB::expr(" OR (sline_a.typeid='9999' and sline_b.typeid={$this->type_id} and sline_b.proid={$product_id})"))
            ->and_where_close()
            ->and_where_open()
            ->where('a.isnever', '=', 0)
            ->where(DB::expr(" OR (sline_a.starttime<{$now_time} and sline_a.endtime>{$now_time})"))
            ->and_where_close()
            ->execute()
            ->count();
        if ($count > 0) {
            return array(
                'code' => $this->application_code,
                'name' => $this->application_name,
                'icon' => $this->icon,
            );
        } else {
            return false;
        }
    }
}
